package com.hehe.controller;

import com.hehe.entity.*;
import com.hehe.service.GoodsService;
import com.hehe.service.UserService;
import com.hehe.util.FileUtil;
import com.hehe.util.IsUserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public ModelAndView index(){
        System.out.println("进入index界面");
        List<GoodsType> lists = goodsService.findAll_type();
        System.out.println("共有记录："+lists.size());

        List<GoodsInfo> infos = goodsService.findShow_goods();

        System.out.println("首页显示商品："+infos.size());

        ModelAndView modelAndView = new ModelAndView("normal/main");
        modelAndView.addObject("typeList", lists);
        modelAndView.addObject("goodsList", infos);

        return modelAndView;
    }

//    @RequestMapping(value = "/main")
//    public ModelAndView main(){
//        System.out.println("进入main界面");
//        List<GoodsType> lists = goodsService.findAll_type();
//        System.out.println("共有记录："+lists.size());
//
//        List<GoodsInfo> infos = goodsService.findShow_goods();
//
//        System.out.println("首页显示商品："+infos.size());
//
//        ModelAndView modelAndView = new ModelAndView("normal/main");
//        modelAndView.addObject("typeList", lists);
//        modelAndView.addObject("goodsList", infos);
//
//        return modelAndView;
//    }

    //进入发布商品界面
    @RequestMapping(value = "/publish")
    public String publish(HttpSession session,Model model){
        IsUserLogin is = new IsUserLogin(session);
        System.out.println("User is login----------->"+ is.IsLogin());
        if( is.IsLogin().equals("yes")){
            //传种类和新旧程度
            List<GoodsType> types = goodsService.findAll_type();
            List<OldLevel> list = goodsService.findAllLevel();
            model.addAttribute("Alltype",types);
            model.addAttribute("Alllevel",list);
            return "normal/publish";
        }

        return "normal/login";

    }



    //分类商品界面
    @RequestMapping(value = "/goods_type")
    public ModelAndView goods_type(@RequestParam("typeId")  int typeId){

        System.out.println(typeId+"=====");
        List<GoodsInfo> ins =  goodsService.findType_goods(typeId);
        System.out.println(ins.size()+"++++++++++++++");
        ModelAndView mav = new ModelAndView("normal/goods_type");
        mav.addObject("goods_type_list",ins);
        return mav;

    }

    //商品详情界面
    @RequestMapping(value = "/goods_details")
    public ModelAndView goods_details(@RequestParam("goodsId") int goodsId){

        //左：该商品详情
        GoodsInfo info =  goodsService.findOneById_goods(goodsId);

        System.out.println(info.toString());

        //右：商品推荐,随机5个
        List<GoodsInfo> lists = goodsService.findType_goods(info.getType_id());
        ArrayList<GoodsInfo> recommend = new ArrayList<GoodsInfo>();
        for(int i=0; i<5;i++){
          int k =  new Random().nextInt(lists.size()-1)+1;
            recommend.add(lists.get(k));
        }
        ModelAndView mav = new ModelAndView("normal/goods_details");
        mav.addObject("goods_recommend",recommend);
        mav.addObject("goods_details",info);

        return mav;

    }

    /**
     * 发布商品
     */

    @RequestMapping(value = "/addGoods")
    public String addGoods(@RequestParam("pic_file") MultipartFile file, GoodsInfo_Table info,
                           HttpServletRequest request,RedirectAttributes attr){

        User user = (User) request.getSession().getAttribute("user");
        FileOutputStream out=null;

        //图片上传
        String url = new FileUtil().createImgDir("Goods_Img",user.getUserid());
        System.out.println(url);
        try {
            byte[] f = file.getBytes();
            String filename = file.getOriginalFilename();
            out = new FileOutputStream(url+filename);
            out.write(f);

            System.out.println(filename);
            //存入数据库
            info.setGoods_img(filename);
        } catch (IOException e) {
            System.out.println("上传失败");
            request.setAttribute("error_msg","上传失败，重新上传");
            return "normal/publish";

        }finally {
            // 完毕，关闭所有链接
            try {
                out.close();
            } catch (IOException e) {
                System.out.println("关闭流失败");
            }
        }



        //改到这里了，先实现一张图片的
        int id = user.getUserid();
        info.setUserid(id);
        System.out.println("用户ID："+id+"产品类型："+ info.getType_id());
        int result =  goodsService.add_goods(info);

        if (result>0){
            attr.addAttribute("typeId", info.getType_id());
            return "redirect:goods_type";
//            return "redirect:goods_type?typeId="+info.getType_id();

        }else{
            request.setAttribute("error_msg","发布失败");
            return "normal/publish";
        }
    }


    @RequestMapping(value = "/showGoodsPic")
    public void findPicFromDisk(@RequestParam("goodsImg") String goodsImg,@RequestParam String userid,HttpServletResponse response ){
        String url=null;
        System.out.println("图片显示+userid："+userid);
        if (goodsImg == null){

            System.out.println("图片参数为空，查看数据库");
        }else{

            url = new FileUtil().getFileUrl()+"Goods_Img\\"+
                     userid+"\\"+ goodsImg;

            System.out.println("============"+url);
        }
        try {
            //图片读取
            FileInputStream in=new FileInputStream(url);
            int i=in.available();
            byte[]data=new byte[i];
            in.read(data);
            in.close();

            //写图片
            OutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            System.out.println("磁盘图片读写出错");
            e.printStackTrace();
        }


    }


    /**
     *  个人中心
     */
    @RequestMapping(value = "/MyCenter")
    public String MyPublish(@RequestParam int userid, Model model){
        System.out.println(userid);
        //我的发布
        List<GoodsInfo> publish_lists = goodsService.findPublish_goods(userid);
        if(publish_lists!=null)
        model.addAttribute("publish_lists",publish_lists);

        //我的收藏
        List<GoodsCollection> coll = goodsService.findByUserId_coll(userid);
        if(null != coll || !coll.isEmpty()){
//            System.out.println((coll.get(0).getGoodsList()).toString());
            model.addAttribute("col_lists",coll);
        }

        //用户消息
        User user = userService.findOneById(userid);
        model.addAttribute("userInfo",user);

        return "normal/personal";
    }


    /**
     * 修改发布
     */
    @RequestMapping(value = "ModifyPublish")
    public String ModifyPublish(@RequestParam int goods_id,Model model) {

        //传种类和新旧程度
        List<GoodsType> types = goodsService.findAll_type();
        List<OldLevel> list = goodsService.findAllLevel();
        model.addAttribute("Alltype",types);
        model.addAttribute("Alllevel",list);
        //原来的数据
        GoodsInfo goodsInfo = goodsService.findOneById_goods(goods_id);
        model.addAttribute("Goods_Info_p",goodsInfo);
        return "normal/changeGoodsInfo";
    }

    //更新发布----不能改图片
    @RequestMapping(value = "UpdatePublish")
    public String UpdatePublish(GoodsInfo_Table info,@RequestParam int gid,HttpServletRequest request){

        System.out.println("goodsid==========="+gid);
        User user = (User) request.getSession().getAttribute("user");

        int id = user.getUserid();
        info.setUserid(id);
        info.setGoods_id(gid);
        System.out.println("用户ID："+id+"产品类型："+ info.getType_id());
        int result =  goodsService.update_goods(info);

        if (result>0){
            return "forward:personal";
        }else{
            request.setAttribute("error","修改失败");
            return "forward:ModifyPublish?goods_id="+gid;
        }
    }


    //删除发布
    @RequestMapping(value = "DeletePublish")
    public String DeletePublish(@RequestParam int goods_id) {

        int result =  goodsService.del_goods(goods_id);

        if (result>0){
            System.out.println("删除成功o(*￣︶￣*)o");
            return "forward:personal";
        }else{
            System.out.println("删除失败o(╥﹏╥)o");
            return "forward:personal";
        }
    }

    /**
     * 我的收藏模块
     */
    //增加收藏
    @RequestMapping(value = "/AddCollection")
    public  String AddCollection(@RequestParam("goods_id") int goods_id,
                                 HttpServletRequest req){

        User user = (User) req.getSession().getAttribute("user");
        if(user==null){
            req.setAttribute("login_msg","请先登录");
            return "normal/login";
        }else{
            goodsService.add_coll(user.getUserid(),goods_id);
            System.out.println("---------------已经收藏啦o(*￣︶￣*)o");
            req.setAttribute("col_msg","已经收藏啦o(*￣︶￣*)o");
            return "redirect:goods_details?goodsId="+goods_id;
        }

    }

    //删除收藏
    @RequestMapping(value = "DeleteCollection")
    public String DeleteCollection(@RequestParam int col_id) {

        int result =  goodsService.del_coll(col_id);

        if (result>0){
            System.out.println("删除成功o(*￣︶￣*)o");
            return "forward:personal";
        }else{
            System.out.println("删除失败o(╥﹏╥)o");
            return "forward:personal";
        }
    }

    /**
     * 卖家主页
     */
    @RequestMapping(value = "Seller_Main")
    public String Seller_Main(@RequestParam int seller_id, Model model){
        System.out.println(seller_id);
        //卖家所有商品
        List<GoodsInfo> publish_lists = goodsService.findPublish_goods(seller_id);
        if(null!=publish_lists) {
            model.addAttribute("seller_lists", publish_lists);
        }

        return "normal/seller_main";
    }

     //他人评价
    @RequestMapping("/ModifyCredit")
    public String ModifyCredit(int sellerid,int status){

        System.out.println(sellerid+"=====用户评价："+status);
        //数据库改变
        userService.update_credit( sellerid, status);
        return "redirect:Seller_Main?seller_id="+sellerid;
    }


}
